<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/bootstrap-table.min.css">
    <link rel="stylesheet" href="/css/jquery-confirm.min.css">
    <link rel="stylesheet" href="/css/pub.css">
    <link rel="stylesheet" href="/css/order.css">
    <link rel="stylesheet" href="/css/font-awesome-all.min.css">
    <style>
        .test-param-group {
            display: flex;
            flex-direction: column;
        }

        .test-param-group .form-check {
            margin-left: 20px;
        }

        .cal-type-body {
            min-height: 100px;
            max-height: 340px;
        }

        .form-check {
            display: flex;
        }

        .form-check .form-check-label {
            width: 120px;
        }

        .form-check .form-control {
            flex: 1;
        }
    </style>
</head>

<body>
    <div class="sync-area mt-3">
        <div class="row">
            <div>
                <h5>演示窗口水印</h5>
                <button class="btn btn-success mb-3 ms-2" id="startMqttSinkBtn" onclick="startWebSocketSink()"><i
                        class="fa-solid fa-circle-play"></i>启动计算</button>
                <button class="btn btn-danger mb-3 ms-2" id="stopMqttSinkBtn" disabled onclick="stopWebSocketSink()"><i
                        class="fa-solid fa-circle-stop"></i>停止计算</button>
                <button class="btn btn-primary mb-3 ms-2" id="restartWebsocket" disabled
                    onclick="onClickRestartWebsocket()"><i class="fa-solid fa-plug"></i>重连Socket</button>
                <div class="message-container p-3 border rounded">
                    <div id="flinkOutput" class="message-body"></div>
                </div>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-12">
                <button class="btn btn-warning" id="clearMessagesBtn" onclick="onClickClearMessages()">
                    <i class="fas fa-trash-alt"></i> 清除消息
                </button>
            </div>
        </div>
    </div>

    <!-- 计算方式选择模态框 -->
    <div class="modal fade" id="calculationModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">选择测试参数</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                        aria-label="Close"></button>
                </div>
                <div class="modal-body cal-type-body  ">
                    <div class="mb-4 test-param-group">
                        <div class="form-check">
                            <label class="form-check-label" for="testElapseSecs">测试时间(秒)</label>
                            <input class="form-control" type="number" id="testElapseSecs" min="15" max="100" step="1"  value="30">
                        </div>
                        <div class="form-check">
                            <label class="form-check-label" for="winLen">窗口长度(秒)</label>
                            <input class="form-control" type="number" id="winLen" min="1" max="15" step="1" value="10">
                        </div>
                        <div class="form-check">
                            <label class="form-check-label" for="winLateness">允许延时(秒)</label>
                            <input class="form-control" type="number" id="winLateness" min="1" max="5" step="1" value="3">
                        </div>
                        <div class="form-check">
                            <label class="form-check-label" for="extraLateness">额外延时(秒)</label>
                            <input class="form-control" type="number" id="extraLateness" min="1"  max="3" step="1" value="2">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmCalculation"
                        onclick="onClickConfirmCalculation()">确定</button>
                </div>
            </div>
        </div>
    </div>
</body>

<script src="/js/jquery-3.7.1.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script src="/js/bootstrap-table.min.js"></script>
<script src="/js/jquery-confirm.min.js"></script>
<script src="/js/pub.js"></script>
<script src="/js/task.js"></script>
<script src="/js/order.js"></script>
<script src="/js/mqtt.js"></script>
<script src="/js/font-awesome-all.min.js" data-auto-replace-svg="nest"></script>
<script>
    // WebSocket连接
    function initWebSocket() {
        if (!window.watermark) {
            window.watermark = {};
        }
        if (window.watermark.wsUri === undefined || window.watermark.wsUri === null) {
            window.watermark.wsUri = getWebsocketUri();
        }
        if (window.watermark.Websocket == undefined || window.watermark.Websocket == null) {
            window.watermark.websocket = null;
        }
        if (window.watermark.websocket != undefined && window.watermark.websocket != null) {
            console.log("WebSocket已存在，无需初始化");
            return;
        }
        console.log("初始化websocket连接");
        let websocket = new WebSocket(window.watermark.wsUri);
        websocket.onopen = function (evt) {
            addMessageToFlinkOut("WebSocket连接已建立");
            //发送消息给服务器，告诉自己的名称
            websocket.send("setName:" + FLINK_TEST_CLICK_AND_WATERMARK);
        };
        websocket.onclose = function (evt) {
            if (window.watermark.websocket != null) {
                //关闭websocket连接
                window.watermark.websocket.close();
                clearInterval(window.watermark.websocketHeartbeatInterval);
                window.watermark.websocket = null;
                addMessageToFlinkOut("关闭webSocket");
            }
            // 启用重连按钮
            document.getElementById('restartWebsocket').disabled = false;
        };
        websocket.onmessage = function (evt) {
            let data = JSON.parse(evt.data);
            if (data.dataIsObject) {
                addMessageToFlinkOut(JSON.stringify(data.data));
            }
            else {
                addMessageToFlinkOut(data.data);
            }
        };
        websocket.onerror = function (evt) {
            // 启用重连按钮
            addMessageToFlinkOut("WebSocket错误: " + evt);
            if (window.watermark.websocket != null) {
                //关闭websocket连接
                window.watermark.websocket.close();
                clearInterval(window.watermark.websocketHeartbeatInterval);
                window.watermark.websocket = null;
                addMessageToFlinkOut("关闭webSocket");
            }
            document.getElementById('restartWebsocket').disabled = false;
        };
        window.watermark.websocket = websocket;

        // 每5秒发送一次心跳
        window.watermark.websocketHeartbeatInterval = setInterval(sendHeartbeat, 5000);
        //充值按钮状态
        document.getElementById('restartWebsocket').disabled = true;
    }

    // 重连按钮点击事件
    function onClickRestartWebsocket() {
        initWebSocket();
    }



    // MQTT Sink按钮点击事件
    function startWebSocketSink() {
        const calcModal = new bootstrap.Modal(document.getElementById('calculationModal'));
        calcModal.show();
    }
    // 停止JDBC Sink按钮点击事件
    function stopWebSocketSink() {
        stopMqttTask(FLINK_TEST_CLICK_AND_WATERMARK, function (result) {
            if (result.data) {
                document.getElementById("startMqttSinkBtn").disabled = false;
                document.getElementById("stopMqttSinkBtn").disabled = true;
            }
        });
    }


    // 发送心跳消息
    function sendHeartbeat() {
        if (window.watermark.websocket && window.watermark.websocket.readyState === WebSocket.OPEN) {
            window.watermark.websocket.send("heartbeat");
        } else {
            console.log("WebSocket未连接，无法发送心跳");
        }
    }



    // 初始化时绑定radio的onclick事件
    $(document).ready(function () {

    });


    // 确认计算方式按钮点击事件
    function onClickConfirmCalculation() {
        if (!validateInput('testElapseSecs', '测试时间不能为空')) return;
        if (!validateInput('winLen', '窗口长度不能为空')) return;
        if (!validateInput('winLateness', '允许延时不能为空')) return;
        if (!validateInput('extraLateness', '额外延时不能为空')) return;

        const calcModal = bootstrap.Modal.getInstance(document.getElementById('calculationModal'));

        let params = {
            "testElapseSecs": $("#testElapseSecs").val(),
            "winLen": $("#winLen").val(),
            "winLateness": $("#winLateness").val(),
            "extraLateness": $("#extraLateness").val()
        };

        calcModal.hide();

        // 调用runTask并传递参数
        runTask(FLINK_TEST_CLICK_AND_WATERMARK, function () {
            document.getElementById("startMqttSinkBtn").disabled = true;
            document.getElementById("stopMqttSinkBtn").disabled = false;
        }, params);
    }


    // 清除消息功能
    function onClickClearMessages() {
        document.getElementById('flinkOutput').innerHTML = '';
    }

    function validateInput(elementId, errorMsg) {
        const value = document.getElementById(elementId).value.trim();
        if (!value) {
            showMessage('参数校验失败', errorMsg, 'warning');
            document.getElementById(elementId).focus();
            return false;
        }
        return true;
    }

    // 初始化WebSocket连接和心跳定时器
    $(document).ready(function () {
        initWebSocket();
        setButtonStatus();
    });

    window.addEventListener("unload", function (event) {
        if (window.watermark.websocketHeartbeatInterval) {
            clearInterval(window.watermark.websocketHeartbeatInterval);
            console.log('已清理心跳定时器');
        }
        if (window.watermark.websocket) {
            window.watermark.websocket.close();
            console.log('已关闭WebSocket连接');
        }
        stopWebSocketSink();
    });
</script>

</html>